package com.spic.business.violation.supervision.speed.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.spic.business.common.core.utils.ValidatorUtil;
import com.spic.business.common.core.workflow.IWorkFlowType;
import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.common.workflow.WorkFlowServiceImpl;
import com.spic.business.enumconst.BusinessType;
import com.spic.business.hik.service.HkSafeService;
import com.spic.business.utils.GroupUtils;
import com.spic.business.violation.supervision.speed.domain.VehicleSpeedRecordDTO;
import com.spic.business.violation.supervision.speed.domain.ViolationsSpeedRecord;
import com.spic.business.violation.supervision.speed.domain.ViolationsSpeedRecordDirty;
import com.spic.business.violation.supervision.speed.mapper.ViolationsSpeedRecordDirtyMapper;
import com.spic.business.violation.supervision.speed.mapper.ViolationsSpeedRecordMapper;
import com.spic.business.violation.supervision.speed.service.IViolationsSpeedRecordService;
import com.spic.business.violation.supervision.speed.service.IViolationsSpeedRulesService;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.common.core.utils.bean.BeanUtils;
import com.spic.common.core.web.domain.AjaxResult;
import com.spic.system.api.RemoteActivitiTaskService;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.groups.Default;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 超速记录Service业务层处理
 *
 * @author yangjie
 * @date 2021-10-12
 */
@Service
public class ViolationsSpeedRecordServiceImpl extends WorkFlowServiceImpl<ViolationsSpeedRecordMapper, ViolationsSpeedRecord> implements IViolationsSpeedRecordService
{
    @Autowired
    private ViolationsSpeedRecordMapper violationsSpeedRecordMapper;

    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private IViolationsSpeedRulesService rulesService;

    @Autowired
    private HkSafeService hkSafeService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private RemoteActivitiTaskService remoteActivitiTaskService;
    @Autowired
    private ViolationsSpeedRecordDirtyMapper violationsSpeedRecordDirtyMapper;

    /**
     * 查询超速记录
     *
     * @param id 超速记录主键
     * @return 超速记录
     */
    @Override
    public ViolationsSpeedRecord selectViolationsSpeedRecordById(Long id)
    {
        return violationsSpeedRecordMapper.selectViolationsSpeedRecordById(id);
    }

    /**
     * 查询超速记录列表
     *
     * @param violationsSpeedRecord 超速记录
     * @return 超速记录
     */
    @Override
    @BusinessDataScope(menuPath = "business/violation/violations_speed_record/index")
    public List<ViolationsSpeedRecord> selectViolationsSpeedRecordList(ViolationsSpeedRecord violationsSpeedRecord)
    {
        List<ViolationsSpeedRecord> violationsSpeedRecordList = violationsSpeedRecordMapper.selectViolationsSpeedRecordList(violationsSpeedRecord);
        if(violationsSpeedRecordList!=null && violationsSpeedRecordList.size()>0){
            processRow(violationsSpeedRecordList, this::row);
        }
        //效率太低，弃用 xuxc 2022-01-08
    /*    for(int i=0;i<violationsSpeedRecordList.size();i++){
            String responsibles = violationsSpeedRecordList.get(i).getResponsible();//责任人
            if(responsibles!=null && !"".equals(responsibles)){
                Long responsible = Long.parseLong(responsibles);
                R<SysUser> sysResponsible = remoteUserService.getUserById(responsible);
                if(sysResponsible.getData()!=null) {
                    violationsSpeedRecordList.get(i).setResponsible(sysResponsible.getData().getUserName());
                }
            }

            String mentionDissolutions = violationsSpeedRecordList.get(i).getMentionDissolution(); //提报人
            if(mentionDissolutions!=null && !"".equals(mentionDissolutions)){
                Long mentionDissolution = Long.parseLong(mentionDissolutions);
                R<SysUser> sysmentionDissolution = remoteUserService.getUserById(mentionDissolution);
                if(sysmentionDissolution.getData()!=null)
                {
                    violationsSpeedRecordList.get(i).setMentionDissolution(sysmentionDissolution.getData().getUserName());
                }
            }
            String acceptors = violationsSpeedRecordList.get(i).getAcceptor(); //验收人
            if(acceptors!=null && !"".equals(acceptors)){
                Long acceptor = Long.parseLong(acceptors);
                R<SysUser> sysacceptor = remoteUserService.getUserById(acceptor);
                if(sysacceptor.getData()!=null)
                {
                    violationsSpeedRecordList.get(i).setAcceptor(sysacceptor.getData().getUserName());
                }
            }
            String associatedDepts = violationsSpeedRecordList.get(i).getAssociatedDept(); //关联部门
            if(associatedDepts!=null && !"".equals(associatedDepts)){
                Long associatedDept = Long.parseLong(associatedDepts);//关联部门
                R<SysDept> sysDeptassociatedDept = remoteUserService.lists(associatedDept);
                if(sysDeptassociatedDept.getData() != null)
                {
                    violationsSpeedRecordList.get(i).setAssociatedDept(sysDeptassociatedDept.getData().getDeptName());
                }
            }
        }*/

        return violationsSpeedRecordList;
    }

    /**
     * 新增超速记录
     *
     * @param violationsSpeedRecord 超速记录
     * @return 结果
     */
    @Override
    public Long insertViolationsSpeedRecord(ViolationsSpeedRecord violationsSpeedRecord)
    {
        violationsSpeedRecord.setCreateTime(DateUtils.getNowDate());
        int i = violationsSpeedRecordMapper.insertViolationsSpeedRecord(violationsSpeedRecord);
        return violationsSpeedRecord.getId();
    }

    /**
     * 修改超速记录
     *
     * @param violationsSpeedRecord 超速记录
     * @return 结果
     */
    @Override
    public int updateViolationsSpeedRecord(ViolationsSpeedRecord violationsSpeedRecord)
    {
        violationsSpeedRecord.setUpdateTime(DateUtils.getNowDate());
        return violationsSpeedRecordMapper.updateViolationsSpeedRecord(violationsSpeedRecord);
    }

    /**
     * 批量删除超速记录
     *
     * @param ids 需要删除的超速记录主键
     * @return 结果
     */
    @Override
    public int deleteViolationsSpeedRecordByIds(Long[] ids)
    {
        return violationsSpeedRecordMapper.deleteViolationsSpeedRecordByIds(ids);
    }

    /**
     * 删除超速记录信息
     *
     * @param id 超速记录主键
     * @return 结果
     */
    @Override
    public int deleteViolationsSpeedRecordById(Long id)
    {
        return violationsSpeedRecordMapper.deleteViolationsSpeedRecordById(id);
    }

    @Override
    public List<HashMap<String, Object>> getillegalSourcesByTime(ViolationsSpeedRecord violationsSpeedRecord)
    {
        return violationsSpeedRecordMapper.getillegalSourcesByTime(violationsSpeedRecord);
    }
    //处理每条业务自己逻辑
    private void row(ViolationsSpeedRecord violationsSpeedRecord)
    {
    }
    @Override
    public List<HashMap<String, Object>> getiillegalTypeByTime(ViolationsSpeedRecord violationsSpeedRecord)
    {
        return violationsSpeedRecordMapper.getiillegalTypeByTime(violationsSpeedRecord);
    }

    @Override
    public List<HashMap<String, Object>> getillegalAreaByTime(ViolationsSpeedRecord violationsSpeedRecord)
    {
        return violationsSpeedRecordMapper.getillegalAreaByTime(violationsSpeedRecord);
    }

    @Override
    public int insertViolationsSpeedRecord(List<VehicleSpeedRecordDTO> vehicleSpeedRecordDTOS) {
        List<ViolationsSpeedRecord> records = rulesService.getOverSpeedRecords(vehicleSpeedRecordDTOS);
        records.forEach(this::insertViolationsSpeedRecord);
        return records.size();
    }

    @Override
    protected IWorkFlowType getWorkFlowType()
    {
        return BusinessType.SPEED;
    }

    @Override
    protected void setWorkFlowVariable(ViolationsSpeedRecord entity, Map<String, Object> variable)
    {
        variable.put("carmanger", getDrafter(entity.getAssociatedDept()));
    }

    /**
     * 获取部门违章管理员id
     * @param deptId 部门id
     * @return 人员id
     */
    public Long getDrafter(String deptId){
        R<SysUser> user = remoteUserService.getWzUserId(deptId);
        return user.getData().getUserId();
    }

    /**
     * 违章车辆车辆布控 违章处理完成取消布防 超速记录
     * @return
     */
    @Override
    public AjaxResult doorOpenOrClose()
    {
        List<ViolationsSpeedRecord> violationsSpeedRecordList = violationsSpeedRecordMapper.selectViolationsSpeedRecordListAll();

        //没开始处理的流程  升序
        List<ViolationsSpeedRecord> collect = violationsSpeedRecordList.stream().filter(f -> StringUtils.isEmpty(f.getInstanceId())&& "0".equals(f.getAlarmCarType())).sorted(Comparator.comparing(ViolationsSpeedRecord::getIllegalTime).reversed()).collect(Collectors.toList());
        //有流程实例的流程  升序
        List<ViolationsSpeedRecord> collect1 = violationsSpeedRecordList.stream().filter(v -> StringUtils.isNotEmpty(v.getInstanceId()) && "0".equals(v.getAlarmCarType()) ).sorted(Comparator.comparing(ViolationsSpeedRecord::getIllegalTime).reversed()).collect(Collectors.toList());
        executor.execute(() -> {
        for (ViolationsSpeedRecord violationsSpeedRecord : collect)
        {
                //车牌号
                String vehicleNumber = violationsSpeedRecord.getVehicleNumber();
                if(StringUtils.isNotEmpty(vehicleNumber)){
                    Map<String,Object> map = new HashMap<>();
                    map.put("plateNo",vehicleNumber);
                    JSONObject json = new JSONObject(map);
                    hkSafeService.alarmCarAddition(json);
                }

        }
        List<ViolationsSpeedRecord> updateByList = new ArrayList<>();
//        collect1.stream().filter(v->!"3".equals(v.getStatus())).map(ViolationsSpeedRecord::getVehicleNumber).collect(Collectors.joining(","));
        List<String> searchKeyList = new ArrayList<>();
        for (ViolationsSpeedRecord violationsSpeedRecord : collect1)
        {
            AjaxResult runTaskInstanceTask = remoteActivitiTaskService.getRunTaskInstanceTask(violationsSpeedRecord.getInstanceId());
            List<String> listTask = (List<String>) runTaskInstanceTask.get("data");
                if( listTask !=null && listTask.size()>0){
                    //车牌号
                    String vehicleNumber = violationsSpeedRecord.getVehicleNumber();
                    if(StringUtils.isNotEmpty(vehicleNumber)){
                        Map<String,Object> map = new HashMap<>();
                        map.put("plateNo",vehicleNumber);
                        JSONObject json = new JSONObject(map);
                        hkSafeService.alarmCarAddition(json);
                    }
                }else{
                    //车牌号
                    String vehicleNumber = violationsSpeedRecord.getVehicleNumber();
                    if(StringUtils.isNotEmpty(vehicleNumber)){
                        Map<String,Object> map = new HashMap<>();
                        map.put("pageNo",1);
                        map.put("pageSize",10);
                        map.put("searchKey",vehicleNumber);
                        JSONObject json = new JSONObject(map);
                        String s = hkSafeService.alarmCarPage(json);
                        searchKeyList.add(s);
                        ViolationsSpeedRecord v = new ViolationsSpeedRecord();
                        v.setId(violationsSpeedRecord.getId());
                        v.setAlarmCarType("1");
                        violationsSpeedRecordMapper.updateViolationsSpeedRecord(v);
                    }
                }
        }

            String value = searchKeyList.stream().collect(Collectors.joining(","));
            Map<String,Object> map = new HashMap<>();
            map.put("alarmSyscodes",value);
            JSONObject json = new JSONObject(map);
            hkSafeService.alarmCarDeletion(json);
        });
        return AjaxResult.success();
    }

    @Override
    public void filterDirtyData() {
        violationsSpeedRecordDirtyMapper.deleteAll();
        ViolationsSpeedRecord violationsSpeedRecord = new ViolationsSpeedRecord();
        violationsSpeedRecord.setIllegalSources("0");
        List<ViolationsSpeedRecord> violationsSpeedRecordList = violationsSpeedRecordMapper.selectViolationsSpeedRecordList(violationsSpeedRecord);
        List<List<ViolationsSpeedRecord>> lists = GroupUtils.groupData(violationsSpeedRecordList, 1000);
        for(List<ViolationsSpeedRecord> list : lists) {
            executor.execute(() -> {
                //System.out.println("~~~~~~~~~~~~~~~~~~" + Thread.currentThread().getName());
                for(ViolationsSpeedRecord record : list) {
                    List<String> validate = ValidatorUtil.validate(record, Default.class);
                    if(validate != null && validate.size() > 0) {
                        String dirtyReason = String.join(",", validate);
                        ViolationsSpeedRecordDirty violationsSpeedRecordDirty = new ViolationsSpeedRecordDirty();
                        violationsSpeedRecordDirty.setIncomplete(1);
                        violationsSpeedRecordDirty.setDirtyReason(dirtyReason);
                        BeanUtils.copyBeanProp(violationsSpeedRecordDirty, record);
                        violationsSpeedRecordDirtyMapper.insertViolationsSpeedRecordDirty(violationsSpeedRecordDirty);
                    }
                }
            });
        }
    }
}
